package view;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.text.SimpleDateFormat;

import javax.swing.JColorChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import control.networking.ChatClient;

import model.Player;

/**
 * The ChatPanel displays both the text box that represents the 
 * log and the submit area to enter in your own text to the
 * conversation.
 * @author Cam Adamson
 *
 */
public class ChatPanel extends JPanel {
	/**
	 * 
	 */
	//private static final long serialVersionUID = 1L;
	
	private JTextField 	chatField;
	private JTextArea 	textArea;
	private Player 		clientPlayer;
	private ChatClient 	client;
	
	/**
	 * Initializes the ChatPanel
	 * @param p
	 */
	public ChatPanel(Player p){
		clientPlayer = p;
		this.setLayout(new BorderLayout());
		
        chatField = new JTextField(30);
        chatField.addActionListener(new TextActionListener() );

        textArea = new JTextArea(7, 30);
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);
       
        this.add(scrollPane, BorderLayout.NORTH);
        this.add(chatField, BorderLayout.SOUTH);

	}
	
	/**
	 * Appends the text sent to the conversation
	 * @param text
	 */
	public void appendText( String text ) {
		textArea.append( text );
		textArea.setCaretPosition(textArea.getDocument().getLength());
	}
	
	/**
	 * Sets the backend ChatClient for the panel
	 * @param cc
	 */
	public void setChatClient( ChatClient cc ) {
		client = cc;
	}
	
	
	private class TextActionListener implements ActionListener{
		SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
		
	    public void actionPerformed(ActionEvent evt) {
	    	System.out.println("Send This");
	    	String toDisplay;
	        String message = chatField.getText();
	        String timeStamp = formatter.format( System.currentTimeMillis() ) + " " + clientPlayer.getName() + ": ";
	        toDisplay = timeStamp + "\t" + message;
	        
	        client.sendMessage( toDisplay );
	        
	        chatField.selectAll();
	        chatField.replaceSelection("");

	        textArea.setCaretPosition(textArea.getDocument().getLength());
	    }
	}
	
	
}
